package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@WebServlet({"/dept/list","/dept/add","/dept/delete","/dept/detail","/dept/edit","/dept/modify"})
public class DeptServlet extends HttpServlet {
    //模板方法
    //重写service方法（并没有重写doGet或者doPost方法）

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取servlet路径
        String path = request.getServletPath();
        if("/dept/list".equals(path)){
            dolist(request,response);
        }else if("/dept/add".equals(path)){
            doAdd(request,response);
        }else if("/dept/delete".equals(path)){
            doDel(request,response);
        }else if("/dept/detail".equals(path)){
            doDetail(request,response);
        }else if("/dept/edit".equals(path)){
            doEdit(request,response);
        }else{
            doModify(request,response);
        }
    }

    private void doModify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");
        String deptno = request.getParameter("deptno");
        String contextPath = request.getContextPath();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out= response.getWriter();
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        int count=0;
        try {
            con= DBUtil.getConnection();
            String sql="update dept set dname=?,loc=? where deptno=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setString(1,dname);
            pstmt.setString(2,loc);
            pstmt.setInt(3,Integer.parseInt(deptno));
            count =pstmt.executeUpdate();
        } catch (SQLException exception) {
            exception.printStackTrace();
        }finally {
            DBUtil.close(con,pstmt,rs);
        }
        if(count==1){
//            request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/dept/list");
        }else{
//            request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/error.html");
        }
    }

    private void doEdit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String deptno = request.getParameter("deptno");
        //获取应用的根路径
        String contextPath = request.getContextPath();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out= response.getWriter();
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        out.println("<!DOCTYPE html>");
        out.println("<html lang='en'>");
        out.println("<head>");
        out.println("    <meta charset='UTF-8'>");
        out.println("    <title>修改部门</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>修改页面</h1>");
        out.println("<form action='"+contextPath+"/dept/modify' method='post'>");
        try {
            con= DBUtil.getConnection();
            String sql="select dname,loc from dept where deptno=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,Integer.parseInt(deptno));
            rs=pstmt.executeQuery();
            if(rs.next()){
                String dname=rs.getString("dname");
                String loc=rs.getString("loc");
                out.println("部门编号：<input type='text' name='deptno' value='"+deptno+"' readonly><br/>");
                out.println("部门名称：<input type='text' name='dname' value='"+dname+"'><br/>");
                out.println("部门位置：<input type='text' name='loc' value='"+loc+"'><br/>");
            }
        } catch (SQLException exception) {
            exception.printStackTrace();
        }finally {
            DBUtil.close(con,pstmt,rs);
        }
        out.println("  <input type='submit' value='修改'><br/>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

    private void doDetail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String deptno=request.getParameter("deptno");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out= response.getWriter();
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        out.println("<!DOCTYPE html>");
        out.println("<html lang='en'> ");
        out.println("<head>      ");
        out.println("    <meta charset='UTF-8'> ");
        out.println("   <title>部门详情</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>部门详情</h1>");
        out.println("<hr/>");
        try {
            con= DBUtil.getConnection();
            String sql="select dname,loc from dept where deptno=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,Integer.parseInt(deptno));
            rs=pstmt.executeQuery();
            if(rs.next()){
                String dname=rs.getString("dname");
                String loc=rs.getString("loc");
                out.println("部门编号："+deptno+"<br/>");
                out.println("部门名称："+dname+"<br/>");
                out.println("部门位置："+loc+"<br/>");
            }
        } catch (SQLException exception) {
            exception.printStackTrace();
        }finally {
            DBUtil.close(con,pstmt,rs);
        }
        out.println("<input type='button' value='后退' onclick='window.history.back()'>");
        out.println("</body>");
        out.println("</html>");
    }

    private void doDel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String deptno=request.getParameter("deptno");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out= response.getWriter();
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        int count=0;
        try {
            con= DBUtil.getConnection();
            con.setAutoCommit(false);
            String sql="delete from dept where deptno=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,Integer.parseInt(deptno));
            count=pstmt.executeUpdate();
            con.commit();
        } catch (SQLException e) {
            if(con!=null){
                try {
                    con.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(con,pstmt,rs);
        }
        if(count==1){
//            request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/dept/list");
        }else{
//            request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/error.html");
        }
    }

    private void doAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String contextPath = request.getContextPath();
        response.setContentType("text/html;charset=utf-8");
        String deptno=request.getParameter("deptno");
        String dname=request.getParameter("dname");
        String loc=request.getParameter("loc");
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        int count=0;
        try {
            con= DBUtil.getConnection();
            String sql="insert into dept(deptno,dname,loc) values(?,?,?)";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,Integer.parseInt(deptno));
            pstmt.setString(2,dname);
            pstmt.setString(3,loc);
            count=pstmt.executeUpdate();
        } catch (SQLException exception) {
            exception.printStackTrace();
        }finally {
            DBUtil.close(con,pstmt,rs);
        }
        if(count==1){
//            request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/dept/list");
        }else{
//            request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/error.html");
        }
    }

    private void dolist(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取应用的根路径
        String contextPath = request.getContextPath();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out= response.getWriter();
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        try {
            con= DBUtil.getConnection();
            String sql="select deptno as a,dname,loc from dept";
            pstmt=con.prepareStatement(sql);
            rs=pstmt.executeQuery();
            out.print("<!DOCTYPE html>");
            out.print("<html lang='en'>");
            out.print("<head>");
            out.print("    <meta charset='UTF-8'>");
            out.print("    <title>List Page</title>");
            out.print("</head>");
            out.print("<body>");
            out.print("<script type='text/javascript'>");
            out.print("        function del(deptno){");
            out.print("    var ok=window.confirm('亲，请确认删除');");
            out.print("    if(ok){");
            out.print("        document.location.href='"+contextPath+"/dept/delete?deptno='+deptno;");
            out.print("    }");
            out.print("}");
            out.print("</script>");
            out.print("<h1 align='center'>部门列表</h1>");
            out.print("<hr/>");
            out.print("<table border='1px' align='center' width='50%'>");
            out.print("    <tr>");
            out.print("        <th>序号</th>");
            out.print("        <th>部门编号</th>");
            out.print("        <th>部门名称</th>");
            out.print("        <th>操作</th>");
            out.print("    </tr>");
            int i=0;
            while (rs.next()){
                String deptno=rs.getString("a");
                String dname=rs.getString("dname");
                String loc=rs.getString("loc");
                out.print("    <tr>");
                out.print("        <td>"+(++i)+"</td>");
                out.print("        <td>"+deptno+"</td>");
                out.print("        <td>"+dname+"</td>");
                out.print("        <td>");
                out.print("            <a href='"+contextPath+"/dept/edit?deptno="+deptno+"'>修改</a>");
                out.print("            <a href='javascript:void(0)' onclick='del("+deptno+")'>删除</a>");
                out.print("            <a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>详情</a>");
                out.print("        </td>");
                out.print("    </tr>");
            }
            out.print("</table>");
            out.print("<hr/>");
            out.print("<a href='"+contextPath+"/add.html'>新增部门</a>");
            out.print("</body>");
            out.print("</html>");
        } catch (SQLException exception) {
            exception.printStackTrace();
        }finally {
            DBUtil.close(con,pstmt,rs);
        }
    }
}
